package global

import (
	"errors"
	"log"
	"os"
	"rustdesk_api_server/models"
	"rustdesk_api_server/utils"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var (
	DB *gorm.DB
)

func Initialize() error {
	mysqlConfig := mysql.Config{
		DSN:                       "lvdao:lvdao@tcp(localhost:3306)/rustdesk_api_server?charset=utf8mb4&parseTime=True&loc=Local",
		DefaultStringSize:         191,
		DisableDatetimePrecision:  true,
		DontSupportRenameIndex:    true,
		DontSupportRenameColumn:   true,
		SkipInitializeWithVersion: false,
	}

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Silent,
			Colorful:      true,
		},
	)

	gormConfig := gorm.Config{
		Logger: newLogger,
	}

	if db, err := gorm.Open(mysql.New(mysqlConfig), &gormConfig); err != nil {
		return err
	} else {
		db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
		sql, _ := db.DB()
		sql.SetMaxIdleConns(10)
		sql.SetMaxOpenConns(100)
		DB = db
	}

	return RegisterTables()
}

func RegisterTables() error {
	if DB == nil {
		return errors.New("database initialize failed")
	}
	err := DB.AutoMigrate(
		models.Peer{},
		models.User{},
		models.Tags{},
	)

	if err != nil {
		log.Fatalln("register table failed, error: ", err.Error())
		return err
	}

	log.Println("register table success")

	var user models.User
	err = DB.First(&user, "username = ?", "admin").Error
	if err == gorm.ErrRecordNotFound {
		user.Username = "admin"
		user.Password = utils.HashPassword("admin")
		DB.Create(&user)
	}

	return nil
}
